﻿using System;
using System.IO;
using System.Web;
using System.Net;
using System.Data;
using System.Text;
using NLBS.Data;
using NLBS.Entity;


namespace NLBS.Syndication
{
    /// <summary>
    /// Trackback类，blog系统的trackback功能支持代码
    /// by bood, 2005.11.25
    /// </summary>
    public class TrackBackWriter
    {
        //预定义返回XML的模板
        private string OkMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
            + "<response>\n"
            + "<error>0</error>\n"
            + "</response>\n";
        private string PreErrorMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
            + "<response>\n"
            + "<error>1</error>\n"
            + "<message>";
        private string PostErrorMsg = "</message>\n"
            + "</response>\n";

        



        //msg=null时返回OkMsg
        //否则msg作为错误信息
        private string RespondMsg(string msg)
        {
            if (msg == null) return OkMsg;
            else return PreErrorMsg + msg + PostErrorMsg;
        }

        //处理trackback ping
        //参数：
        //request：传入相应HttpRequest对象（封装了处理POST参数过程）
        //parentId：文章的id
        public string ProcessPing(HttpRequest request)
        {
            if (request == null || request.QueryString["id"]==null)
            {
                return RespondMsg("Invalid blog item referred.");
            }

            //标准规定：必须是POST请求
            if (!request.HttpMethod.Equals("POST"))
                return RespondMsg("Request MUST submitted in POST method.");

            string title = request.Form["title"];
            string url = request.Form["url"];
            string excerpt = request.Form["excerpt"];
            string blog_name = request.Form["blog_name"];
            string ip = request.UserHostAddress;

            if (null == title || 0 == title.Length) title = url;
            title = CutLeft(title, 30);

            //标准规定：必须指定url字段
            if (url == null || url.Trim().Length == 0)
                return RespondMsg("The \"url\" not specified in the POST request.");
           TrackBack tb=new TrackBack();
           tb.Title = title;
           tb.Url = url;
           tb.Excerpt = excerpt;
           tb.BlogName = blog_name;
           tb.IP = ip;
           tb.Time = DateTime.Now;
           tb.LogID =Convert.ToInt32(request.QueryString["id"]);
           DbProvider.Instance().InsertTrackBack(tb);
            return string.Empty;
        }

        //发出trackback ping
        //参数：
        //targetUrl：目标trackback链接地址
        //blog_name,title,excerpt可为null
        //url必须指定为发起ping的文章对应的链接（标准规定）
        //异常：
        //WebException：域名解析错误/处理请求错误
        public void SendPing(string targetUrl, string url, string blog_name,
            string title, string excerpt)
        {
            HttpWebRequest post = (HttpWebRequest)WebRequest.Create(targetUrl);

            //标准规定
            post.Method = "POST";
            post.ContentType = "application/x-www-form-urlencoded; charset=utf-8";

            //构造POST数据
            string postData = "";
            if (url != null) postData += "url=" + HttpUtility.UrlEncode(url);
            if (blog_name != null) postData += "&blog_name=" + HttpUtility.UrlEncode(blog_name);
            if (title != null) postData += "&title=" + HttpUtility.UrlEncode(title);
            if (excerpt != null) postData += "&excerpt=" + HttpUtility.UrlEncode(excerpt);

            //将POST数据写入request流
            //utf-8编码
            byte[] buff = Encoding.UTF8.GetBytes(postData);
            post.ContentLength = buff.Length;
            Stream stream = post.GetRequestStream();
            stream.Write(buff, 0, buff.Length);
            stream.Close();
            try
            {
                post.BeginGetResponse(null, null);
            }
            catch (System.Exception e)
            {
                throw e; 
            }
            //异步调用发出POST，不回调
            
        }

        //截取左侧字符串,若长度超过用……代替
        protected string CutLeft(string s, int len)
        {
            string s2 = s;
            if (s2.Length > len) return s2.Substring(0, len - 2) + "……";
            return s;
        }
    }
}
